<template>
    <div class="app-container contractContainer">
        <div class="customContainer ">
            <!-- 搜索头 -->
            <div class="customHeader">
                <el-button class="pull-right" type="primary" size="small" @click="showUploadDialog()">上传合同</el-button>
            </div>
            <!-- 表格 -->
            <el-table  highlight-current-row :data="list" v-loading.body="listLoading" border size="small">
                <el-table-column align="center" label='合同名称' prop="name"></el-table-column>
                <el-table-column align="center" label='上传时间' prop="create_time"></el-table-column>
                <el-table-column align="center" label='使用门店' prop="grade_name">
                    <template slot-scope="scope">
                        <el-button type="text" size="mini" @click="storeDialogShow(scope.row.id,scope.$index)">配置门店</el-button>
                    </template>
                </el-table-column>
                <el-table-column align="center" label='合同详情'>
                    <template slot-scope="scope">
                        <el-button type="text" size="mini" @click="showUploadDialog(scope.row,scope.$index)">查看</el-button>
                    </template>
                </el-table-column>
                <el-table-column align="center" label='操作'>
                    <template slot-scope="scope">
                        <el-button v-if="scope.row.is_enable == 1" type="success" size="mini" @click="stateClick(scope.row.id,scope.$index,0)">已启用</el-button>
                        <el-button v-else size="mini" @click="stateClick(scope.row.id,scope.$index,1)">已停用</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 配置门店弹框 -->
            <el-dialog :close-on-click-modal="false"  width="700px" title="配置门店" :visible.sync="storeDialog" append-to-body @close="storeCallOf()">
                <!-- 表格 -->
                <div style="overflow: hidden;">
                    <div style="width: 260px" class="pull-left pzmd1">
                        <div style="border: 1px solid #f5f7fa;">
                            <header style="height: 32px;background: #f5f7fa;width: 261px;text-align: center;line-height: 32px;position:relative">请选择门店
                                <span style="position:absolute;right:10px">{{selectLength}}/{{allLength}}</span>
                            </header>
                            <el-select size="small" v-model="brand" placeholder="请选择品牌" @change="brandChange" style="width: 260px">
                                <el-option v-for="item in brand_list" :key="item.id" :label="item.name" :value="item.id">
                                </el-option>
                            </el-select>
                            <div class="el-transfer-panel__filter el-input el-input--small el-input--prefix" style="width:230px">
                                <el-input placeholder="请输入门店名称" size="small" v-model="store_name"></el-input>
                            </div>
                        </div>
                        <el-table  highlight-current-row style="border-right: 1px solid #f5f7fa; border-left: 1px solid #f5f7fa; " :data="new_store_list"
                            v-loading.body="listLoading" fit size="mini"
                            :show-header="false" ref="multipleTable">
                            <!-- <el-table-column type="selection" width="30"></el-table-column> -->
                            <el-table-column>
                                <template slot-scope="scope">
                                    <el-checkbox :disabled="scope.row.is_disabled" v-model="scope.row.is_select"
                                        @change="selectStoreChange(store_list,1)">{{scope.row.name}}</el-checkbox>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div style="border: 1px solid #f5f7fa;">
                            <footer style="height: 32px;background: #f5f7fa;width: 259px;padding-left:10px;line-height: 32px">
                                <el-checkbox v-model="allSelect1" @change="toggleSelect(new_store_list,allSelect1,'add',1)">全选</el-checkbox>
                            </footer>
                        </div>
                    </div>
                    <div class="pull-left" style=" text-align: center;width: 140px;margin-top: 200px;">
                        <el-button type="danger" size="small" @click="delStore" :disabled="!is_del">
                            <i class="el-icon-arrow-left"></i> 删 除</el-button>
                        <br>
                        <br>
                        <el-button type="primary" size="small" @click="addStore" :disabled="!is_add">添 加
                            <i class="el-icon-arrow-right"></i>
                        </el-button>
                    </div>
                    <div style="width:260px;" class="pull-right pzmd2">
                        <div style="border: 1px solid #f5f7fa;">
                            <header style="height: 32px;background: #f5f7fa;width: 261px;text-align: center;line-height: 32px">已选择门店</header>
                        </div>
                        <el-table  highlight-current-row style="border-right: 1px solid #f5f7fa;border-left: 1px solid #f5f7fa; " :data="deploy_store_list"
                            v-loading.body="listLoading" fit size="mini"
                            :show-header="false">
                            <!-- <el-table-column type="selection" width="30"></el-table-column> -->
                            <el-table-column>
                                <template slot-scope="scope">
                                    <el-checkbox v-model="scope.row.is_select" @change="selectStoreChange(deploy_store_list,2)">{{scope.row.name}}</el-checkbox>
                                </template>
                            </el-table-column>
                        </el-table>
                        <footer style="height: 32px;background: #f5f7fa;width: 261px;padding-left:10px;line-height: 32px">
                            <el-checkbox v-model="allSelect2" @change="toggleSelect(deploy_store_list,allSelect2,'del')">全选</el-checkbox>
                        </footer>
                    </div>
                </div>
                <br>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="saveStoreClick" size="small">确认</el-button>
                </div>
            </el-dialog>
            <!-- 上传合同弹框 -->
            <el-dialog :close-on-click-modal="false"  width="80%" title="上传合同" :visible.sync="uploadDialog" append-to-body @close="callOf('saveForm')">
                <el-form :model="saveForm" :rules="rules" ref="saveForm" class="demo-form-inline">
                    <el-form-item label="合同名称" prop="name">
                        <el-input placeholder="请输入合同名称" v-model="saveForm.name" :maxlength="20" :disabled="is_look"></el-input>
                    </el-form-item>
                    <el-form-item label="合同内容" prop="container">
                        <el-input type="textarea" :rows="15" placeholder="请输入合同内容" v-model="saveForm.container"
                            :disabled="is_look"></el-input>
                    </el-form-item>
                    <!-- <el-form-item label="上传合同" required>
                        <el-upload drag ref="upload" action="" :before-upload="beforeUpload" :on-preview="handlePreview" :on-remove="handleRemove"
                            :file-list="fileList" :auto-upload="false" :limit="1">
                            <el-button slot="trigger" size="small" type="text">选取文件或者拖拽进来</el-button>
                        </el-upload>
                    </el-form-item> -->
                </el-form>
                <div slot="footer" class="dialog-footer" v-if="!is_look">
                    <el-button type="primary" @click="saveContractClick('saveForm')" size="small">确认上传</el-button>
                </div>
            </el-dialog>
        </div>
        <!-- 自定义底部 -->
        <div class="bottom_box">
            <el-pagination class="pull-left" background @current-change="handleCurrentChange" :current-page.sync="currentPage"
                :page-size="20" layout="prev, pager, next, jumper" :total="totalDataNumber">
            </el-pagination>
        </div>
    </div>
</template>

<script>
    import {
        getList,
        getPage,
        state,
        storeList,
        brandList,
        saveStore,
        getContract,
        saveContract
    } from "@/api/member/contract_template";
    import Cookies from 'js-cookie'
    import axios from 'axios'

    export default {
        data() {
            return {
                selectLength: 0,
                allLength: 0,
                allSelect1: false,
                allSelect2: false,
                list: null,
                listLoading: false,
                uploadDialog: false,
                storeDialog: false,
                is_add: false,
                is_del: false,
                is_look: false,
                currentPage: 1,
                totalDataNumber: 1,
                store_name: '',
                store_list: [],
                deploy_store_list: [],
                brand_list:null,
                selectFrom1: [],
                selectFrom2: [],
                brand: '',
                storeForm: {
                    id: '',
                    store_list: [],
                },
                value: '',
                saveForm: {
                    name: '',
                    container: ''
                },
                rules: {
                    name: [
                        { required: true, message: '请输入合同名称', trigger: 'blur' }
                    ],
                    container: [
                        { required: true, message: '请输入合同内容', trigger: 'blur' }
                    ],
                },
                fileList: []
            };
        },
        beforeRouteEnter(to, from, next) {
            next((vm) => {//当进入组件之前，执行 beforRouteEnter 路由钩子函数 ,//参数vm就是当前组件的实例。
                if (!vm.brand_list) {
                    vm.getBrandList();
                    vm.fetchData();
                }
            })
        },
        computed: {
            // 前端模糊查询过滤器
            new_store_list() {
                var that = this;
                var new_store_list = [];
                this.store_list.map(function (item) {
                    if (item.name.search(that.store_name) != -1) {
                        new_store_list.push(item);
                    }
                });
                return new_store_list;
            }
        },
        methods: {
            addStore() {
                const that = this;
                this.store_list.forEach(function (val, index) {
                    if (val.is_select) {
                        // console.log(val)
                        that.deploy_store_list.push({
                            id: val.id,
                            is_select: false,
                            name: val.name
                        })
                    }
                });
                this.deploy_store_list = this.unique(this.deploy_store_list, 'id');
                this.store_list.forEach(function (val, index) {
                    val.is_select = false;
                });
                this.getStoreList();
                this.selectLength = 0;
                this.allSelect1 = false;
                this.is_add = false;
            },
            delStore() {
                // 过滤器删除
                this.deploy_store_list = this.deploy_store_list.filter(function (i) { return !i.is_select });
                this.getStoreList();
                this.allSelect2 = false;
                this.is_del = false;
            },
            // 排重参数1数组，参数2key值
            unique(arra, key) {
                var arr = arra;
                var n = [arr[0]];
                for (var i = 1; i < arr.length; i++) {
                    if (key === undefined) {
                        if (n.indexOf(arr[i]) == -1) n.push(arr[i]);
                    } else {
                        inner: {
                            var has = false;
                            for (var j = 0; j < n.length; j++) {
                                if (arr[i][key] == n[j][key]) {
                                    has = true;
                                    break inner;
                                }
                            }
                        }
                        if (!has) {
                            n.push(arr[i]);
                        }
                    }
                }
                return n;
            },
            selectStoreChange(rows, allSelect) {
                let len = 0;
                let not_all = false;
                for (let i = 0; i < rows.length; i++) {
                    if (rows[i].is_select == true) {
                        len++
                    }
                }
                if (allSelect == 1) {
                    this.selectLength = len
                }
                for (let i = 0; i < rows.length; i++) {
                    if (rows[i].is_select == false) {
                        not_all = true;
                        break;
                    }
                }
                if (len > 0) {
                    (allSelect == 1) ? this.is_add = true : this.is_del = true;
                } else {
                    (allSelect == 1) ? this.is_add = false : this.is_del = false;
                }
                if (not_all) {
                    (allSelect == 1) ? this.allSelect1 = false : this.allSelect2 = false;
                } else {
                    (allSelect == 1) ? this.allSelect1 = true : this.allSelect2 = true;
                }
            },
            toggleSelect(rows, allSelect, type, is_left) {
                if (allSelect) {
                    for (let i = 0; i < rows.length; i++) {
                        rows[i].is_select = true
                    }
                    (type == 'add') ? this.is_add = true : this.is_del = true;
                    if (is_left) {
                        this.selectLength = rows.length
                    }
                } else {
                    for (let i = 0; i < rows.length; i++) {
                        rows[i].is_select = false
                    }
                    (type == 'add') ? this.is_add = false : this.is_del = false;
                    this.selectLength = 0
                }
            },
            // beforeUpload(file) {
            //     const that = this
            //     // if (file.name.substring(file.name.length - 3) != 'pdf') {
            //     //     that.$message({ type: 'error', message: '请选择pdf文件上传' });
            //     //     return;
            //     // }
            //     let formData = new FormData();
            //     formData.append('key', file);
            //     formData.append('name', this.saveForm.name);
            //     let url = `https://${location.host}/smsi/index.php/Contract/contract_upload`;
            //     let config = {
            //         headers: { 'didixueshengka': `${Cookies.get('SMS_AdminToken')}` }
            //     };
            //     axios.post(url, formData, config).then(function (response) {
            //         that.$message({ type: response.data.code == 1 ? 'success' : 'error', message: response.data.message });
            //         if (response.data.code == 1) {
            //             that.$refs['saveForm'].resetFields();
            //             that.fetchData();
            //             that.uploadDialog = false;
            //         }
            //     })
            //     return false;
            // },
            // submitUpload() {
            //     this.$refs.upload.submit();
            // },
            handleRemove(file, fileList) {
                console.log(file, fileList);
            },
            handlePreview(file) {
                console.log(file);
            },
            stateClick(id, index, is_enable) {
                let text = is_enable == '1' ? '确认启用' : '确认停用'
                this.$confirm(text, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    state({ id: id, is_enable: is_enable }).then(response => {
                        this.$message({ type: response.code == 1 ? 'success' : 'error', message: response.message });
                        if (response.code == 1) {
                            this.list[index].is_enable = is_enable == 1 ? 1 : 0
                        }
                    });
                })
            },
            showUploadDialog(row, index) {
                this.is_look = row ? true : false;
                this.uploadDialog = true;
                if (row) {
                    getContract({ id: row.id }).then(response => {
                        this.saveForm = response
                        this.saveForm.name = row.name
                    });
                }
            },
            // saveUploadClick(formName) {
            //     this.$refs[formName].validate((valid) => {
            //         if (valid) {
            //             this.submitUpload();
            //         } else {
            //             console.log('error submit!!');
            //             return false;
            //         }
            //     });
            // },
            saveContractClick(formName) {
                const that = this
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        saveContract(this.saveForm).then(response => {
                            that.$message({ type: response.code == 1 ? 'success' : 'error', message: response.message });
                            that.$refs['saveForm'].resetFields();
                            this.handleCurrentChange(this.currentPage);
                            that.uploadDialog = false;
                        });
                    }
                });
            },
            saveStoreClick() {
                const that = this;
                that.storeForm.store_list = [];
                this.deploy_store_list.forEach(function (val, index) {
                    that.storeForm.store_list.push(val.id)
                });
                saveStore(this.storeForm).then(response => {
                    that.$message({ type: response.code == 1 ? 'success' : 'error', message: response.message });
                    if (response.code == 1) {
                        this.handleCurrentChange(this.currentPage)
                        this.storeDialog = false
                    }
                });
            },
            storeDialogShow(id, index) {
                this.deploy_store_list = []
                this.getBrandList();
                this.storeForm.id = id;
                this.deploy_store_list = this.list[index].store_list
                // console.log(this.list[index].store_list)
                this.storeDialog = true;
            },
            brandChange() {
                this.selectLength = 0;
                this.getStoreList();
            },
            getBrandList() {
                brandList({ org: 1, category_id: 273 }).then(response => {
                    this.brand = response[0].id
                    this.brand_list = response
                    this.getStoreList();
                });
            },
            getStoreList() {
                storeList({ brand: this.brand, category_id: 273 }).then(response => {
                    for (let i = 0; i < response.length; i++) {
                        response[i].is_select = false
                        for (let j = 0; j < this.deploy_store_list.length; j++) {
                            if (response[i].id == this.deploy_store_list[j].id) {
                                response[i].is_disabled = true;
                            }
                        }
                    }
                    this.allLength = response.length
                    this.store_list = response
                    this.allSelect1 = false;
                    this.allSelect2 = false;
                });
            },
            // // 表单认证
            // resetForm(formName) {
            //     this.$refs[formName].resetFields();
            // },
            storeCallOf() {
                this.store_name = '';
                // this.handleCurrentChange(this.currentPage);
            },
            // //关闭弹框重置
            callOf(formName) {
                this.$refs['saveForm'].resetFields();
                // this.uploadDialog = false;
                // this.$refs[formName].resetFields();
            },
            // 列表获取
            fetchData() {
                this.listLoading = true;
                getPage({}).then(response => {
                    this.totalDataNumber = response.page * 20;
                    getList({}).then(response => {
                        for (let i = 0; i < response.length; i++) {
                            for (let j = 0; j < response[i].store_list.length; j++) {
                                response[i].store_list[j].is_select = false
                                response[i].store_list[j].is_disabled = false
                                // console.log(j)
                            }
                        }
                        this.list = response;
                        this.listLoading = false;
                    })
                }).catch(res=>{
                    this.listLoading=false;
                })
            },
            handleCurrentChange(val) {
                this.listLoading = true;
                getList({}, val).then(response => {
                    for (let i = 0; i < response.length; i++) {
                        for (let j = 0; j < response[i].store_list.length; j++) {
                            response[i].store_list[j].is_select = false
                            response[i].store_list[j].is_disabled = false
                        }
                    }
                    this.list = response;
                    this.listLoading = false;
                });
            },
        }
    };
</script>
<style>
    .pzmd1 .el-table__body-wrapper {
        max-height: 300px;
    }

    .pzmd2 .el-table__body-wrapper {
        height: 398px;
    }
</style>